'use server'
import { auth } from "@/auth";
import { prisma } from "@/prisma";
import { revalidatePath } from "next/cache";
import z from "zod";

const schema = z.object({
  content: z.string().min(3, "评论内容不能少于3个字符"),
})

interface CreateCommentFormState {
  errors: {
    content?: string[];
    _form?: string[];
  };
  success?: boolean
}

export async function createComment({ postId, parentId }: { postId: string, parentId?: string }, formState: CreateCommentFormState, formData: FormData): Promise<CreateCommentFormState> {
  
  // 判断参数是否正确
  const content = formData.get("content");
  const result = schema.safeParse({
    content,
  })
  if (!result.success) {
    return {
      errors: result.error.flatten().fieldErrors,
    }
  }
  //判断用户是否登录
  const session = await auth()
  if (!session?.user) {
    return {
      errors: {
        _form: ["请先登录"],
      }
    }
  }
  try {
    await prisma.comment.create({
      data: {
        content: result.data.content,
        userId: session.user.id,
        postId,
        parentId: parentId || null,
      }
    })
  } catch (error) {
    if (error instanceof Error) {
      return {
        errors: {
          _form: [error.message],
        }
      }
    } else {
      return {
        errors: {
          _form: ["创建失败"],
        }
      }
    }
  }
  const topic = await prisma.topic.findFirst({
    where: {
      posts: {
        some: {
          id: postId,
        }
      },
    }
  })
  if (!topic) {
    return {
      errors: {
        _form: ["话题不存在"],
      }
    }
  }
  revalidatePath(`/topics/${topic.name}/posts/${postId}`)
  return {
    errors: {},
    success: true
  }
}